var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Goods = require('./../models/goods');
var Users = require('./../models/users');

// 连接mongoDb数据库
mongoose.connect('mongodb://127.0.0.1:27017/ego',{
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
mongoose.connection.on('connected', () => { // 连接成功
    console.log('connected successful');
});
mongoose.connection.on('error', () => { // 连接出错
    console.log('connected error');
});
mongoose.connection.on('disconnected', () => { // 断开连接
    console.log('connected disconnected');
});

// 获取列表数据：排序、筛选、懒加载、分页
router.get('/list', (req, res, next) => {
    let page = req.param('page');
    let pageSize = parseInt(req.param('pageSize'));
    let sort = req.param('sort');
    let startPrice = req.param('startPrice');
    let endPrice = req.param('endPrice');
    let skip = (page -1) * pageSize;
    let params = {};
    if (startPrice && endPrice) {
        params = {
            salePrice: {
                $gt:startPrice,
                $lte:endPrice
            }
        };
    }
    let goodsModel = Goods.find(params).skip(skip).limit(pageSize);
    goodsModel.sort({'salePrice':sort});
    goodsModel.exec((err, doc) => {
        if (err) {
            res.json({
                status: 1,
                msg: err.message
            });
        } else {
            res.json({
                status: 0,
                msg: '',
                result: {
                    count: doc.length,
                    list: doc
                }
            });
        }
    })
})

// 加入购物车
router.post('/addCart', (req, res, next) => {
    let productId = req.body.productId;
    let userId = '100000077';
    Users.findOne({userId: userId}, (errUser, userDoc) => {
        if (errUser) {
            res.json({
                status: '1',
                msg: errUser.message
            });
        } else {
            let hasSameGood = false;
            userDoc.cartList.forEach(good => {
                if (good.productId == productId) {
                    hasSameGood = true;
                    good.productNum ++;
                }
            });
            if (hasSameGood) {
                userDoc.save((errSave, saveDoc) => {
                    if (errSave) {
                        res.json({
                            status: '1',
                            msg: errSave.message
                        })
                    } else {
                        res.json({
                            status: '0',
                            msg: '加入购物车成功',
                            result: 'success'
                        })
                    }
                })
            } else {
                Goods.findOne({productId: productId}, (errGoods,goodsDoc) => {
                    if (errGoods) {
                        res.json({
                            status: '1',
                            msg: errGoods.message
                        })
                    } else {
                        if (goodsDoc) {
                            goodsDoc.productNum = 1;
                            userDoc.cartList.push(goodsDoc);
                            userDoc.save((errSave, saveDoc) => {
                                if (errSave) {
                                    res.json({
                                        status: '1',
                                        msg: errSave.message
                                    })
                                } else {
                                    res.json({
                                        status: '0',
                                        msg: '加入购物车成功',
                                        result: 'success'
                                    })
                                }
                            })
                        }
                    }
                })
            }
        }
    })
})

module.exports = router;